#include "execution/smart_router.h"
#include <algorithm>
#include <cmath>
#include <spdlog/spdlog.h>
#include <memory>

namespace hft {

SmartOrderRouterImpl::SmartOrderRouterImpl(std::shared_ptr<OrderExecutor> executor)
    : executor_(executor), max_slippage_(0.001), min_liquidity_(1000) {
}

bool SmartOrderRouterImpl::routeOrder(const Order& order) {
    std::lock_guard<std::mutex> lock(books_mutex_);
    auto it = order_books_.find(order.symbol);
    if (it == order_books_.end()) {
        spdlog::warn("No order book data for {}", order.symbol);
        return false;
    }
    
    const OrderBook& book = it->second;
    
    // 详细记录订单信息
    spdlog::debug("Routing order: {} {} {} shares @ {}",
                order.symbol, 
                order.side == OrderSide::BUY ? "BUY" : "SELL",
                order.volume,
                order.price);
    
    // 检查流动性
    LiquidityCheckResult liquidity = checkLiquidity(order, book);
    if (!liquidity.sufficient) {
        spdlog::warn("Insufficient liquidity for {}: available={}, required={}",
                   order.symbol, liquidity.available, order.volume);
        return false;
    }
    
    // 检查滑点
    SlippageCheckResult slippage = checkSlippage(order, book);
    if (!slippage.acceptable) {
        spdlog::warn("Slippage too high for {}: {:.4f}% (max {:.4f}%)",
                   order.symbol, 
                   slippage.actual * 100,
                   max_slippage_ * 100);
        return false;
    }
    
    // 根据市场情况调整订单价格
    Order routed_order = order;
    if (order.side == OrderSide::BUY) {
        routed_order.price = std::min(order.price, book.asks[0].first * (1.0 + max_slippage_));
    } else {
        routed_order.price = std::max(order.price, book.bids[0].first * (1.0 - max_slippage_));
    }
    
    spdlog::info("Routing order {}: adjusted price from {} to {}",
               order.order_id, order.price, routed_order.price);
    
    // 提交订单
    return executor_->submitOrder(routed_order);
}

bool SmartOrderRouterImpl::batchRouteOrders(const std::vector<Order>& orders) {
    std::lock_guard<std::mutex> lock(books_mutex_);
    bool all_success = true;
    
    for (const auto& order : orders) {
        if (!routeOrder(order)) {
            all_success = false;
            spdlog::error("Failed to route order {}", order.order_id);
        }
    }
    
    return all_success;
}

void SmartOrderRouterImpl::onOrderBookUpdate(const OrderBook& book) {
    std::lock_guard<std::mutex> lock(books_mutex_);
    order_books_[book.symbol] = book;
}

void SmartOrderRouterImpl::onMarketData(const MarketDataMessage& msg) {
    // 市场数据更新时，更新订单�?
    OrderBook book;
    book.symbol = msg.symbol;
    book.timestamp = msg.timestamp;
    
    // 更新买卖�?
    if (msg.bid_volume > 0) {
        book.bids.emplace_back(msg.bid_price, msg.bid_volume);
    }
    if (msg.ask_volume > 0) {
        book.asks.emplace_back(msg.ask_price, msg.ask_volume);
    }
    
    onOrderBookUpdate(book);
}

void SmartOrderRouterImpl::onOrderUpdate(const Order& order) {
    // 订单更新时，可能需要调整路由策�?
    // 这里可以根据订单执行情况来调整滑点和流动性要�?
}

void SmartOrderRouterImpl::setMaxSlippage(double max_slippage) {
    max_slippage_ = max_slippage;
}

void SmartOrderRouterImpl::setMinLiquidity(int64_t min_liquidity) {
    min_liquidity_ = min_liquidity;
}

SmartOrderRouterImpl::LiquidityCheckResult 
SmartOrderRouterImpl::checkLiquidity(const Order& order, const OrderBook& book) {
    LiquidityCheckResult result;
    
    if (order.side == OrderSide::BUY) {
        // 检查卖盘流动性
        for (const auto& ask : book.asks) {
            if (ask.first <= order.price) {
                result.available += ask.second;
            }
        }
        result.sufficient = result.available >= min_liquidity_;
        
        // 记录详细流动性信息
        spdlog::debug("Buy liquidity check: available={}, required={}, price={}",
                     result.available, order.volume, order.price);
    } else {
        // 检查买盘流动性
        for (const auto& bid : book.bids) {
            if (bid.first >= order.price) {
                result.available += bid.second;
            }
        }
        result.sufficient = result.available >= min_liquidity_;
        
        // 记录详细流动性信息
        spdlog::debug("Sell liquidity check: available={}, required={}, price={}",
                     result.available, order.volume, order.price);
    }
    
    return result;
}

SmartOrderRouterImpl::SlippageCheckResult 
SmartOrderRouterImpl::checkSlippage(const Order& order, const OrderBook& book) {
    SlippageCheckResult result;
    
    if (book.bids.empty() || book.asks.empty()) {
        result.acceptable = false;
        return result;
    }
    
    // 计算中间价
    double mid_price = (book.bids[0].first + book.asks[0].first) / 2.0;
    result.actual = std::abs(order.price - mid_price) / mid_price;
    result.acceptable = result.actual <= max_slippage_;
    
    // 记录详细滑点信息
    spdlog::debug("Slippage check: actual={:.4f}%, max={:.4f}%, price={}, mid={}",
                 result.actual * 100, max_slippage_ * 100, 
                 order.price, mid_price);
    
    return result;
}

} // namespace hft 